<?php

namespace Admin\Controller;

use Think\Controller;

class OrderController extends CommonController
{

    /**
     * 公告部分  公告前三条
     * */
    public function notice_front()
    {
        $data = M('notice', '', 'KEFU')->limit(0, 3)->where(['status' => 1, 'type' => 1])->order('ctime desc')->field('content')->select();
        $this->assign(array('data' => $data)
        );
        $this->display();
    }

    public function notice()
    {
        $n = I('page',1);//
        $num = 8;//一页几条
        $page=($n-1)*$num;

        $total = M('notice', '', 'KEFU')->where(['status' => 1, 'type' => 1])->count();//总数
        $page_num = ceil($total / $num);//页数
        $data = M('notice', '', 'KEFU')->where(['status' => 1, 'type' => 1])->order('ctime desc')->limit($page, $num)->field('content,id,title,name,ctime,apart_id')->select();
        foreach ($data as $k => $v) {
            $data[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
        }
        $this->assign(array(
                'data' => $data,
                'pageNum' => $page_num,
            )
        );
        $this->display();
    }

    /**
     * 公告部分  公告列表
     * */
    public function notice_list()
    {
        $n = I('page');//
        $num = 8;//一页几条
        $page=($n-1)*$num;
        $total = M('notice', '', 'KEFU')->where(['status' => 1, 'type' => 1])->count();//总数
        $page_num = ceil($total / $num);//页数
        $data = M('notice', '', 'KEFU')->where(['status' => 1, 'type' => 1])->order('ctime desc')->limit($page, $num)->field('content,id,title,name,ctime,apart_id')->select();
        foreach ($data as $k => $v) {
            $data[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
        }
        $this->ajaxReturn(['code'=>'1001','page'=>$page_num,'result'=>$data]);
    }
    /**
     * 公告部分  公告详情
     * */
    public function notice_details()
    {
         $id=I('id');
         $data= M('notice', '', 'KEFU')->where(['status' => 1, 'type' => 1,'id'=>$id])->field('title,content,name,ctime,apart_id')->find();
         $data['ctime']=date('Y-m-d H:i' ,$data['ctime']);
         $data['apart']=M('apart','','KEFU')->where(['id'=>$data['apart_id']])->getField('name');
        $this->assign(array(
                'data' => $data,
            )
        );
        $this->display();
    }
    /**
     * 创建工单 界面
     * */
    public function create_order()
    {
        $apart = M('apart', '', 'KEFU')->where(['id'=>['neq',3]])->order('sort desc')->select();
        $this->apart=$apart;
        $this->admin=M('admin', '', 'KEFU')->where(['role_id'=>['in','1,2'],'status'=>1])->field('id,name')->order('id desc')->select();
        $this->display();
    }

    /**
     * 获取部门人员
     * */
    public function getaccept_name(){
        $apart=I('apart');
        switch ($apart){
            case 1://客服
                $admin = M('admin', '', 'KEFU')->where(['role_id' => ['in', '1,2'], 'status' => 1])->field('id,name')->order('id desc')->select();
                break;
            case 2://运营 吴登密  王翎  陈秋利
                $admin = M('admin', '', 'USER')->where(['id' => ['in', '58,63,53'], 'status' => 1])->field('id,name')->select();
                break;
            case 4://风控
                $admin = M('fk_admin', '', 'KEFU_FK')->where(['id' => ['in', '1,6,7,8,13,14'], 'status' => 1])->field('id,name')->select();
                break;
            case 5://后端
                $admin = M('admin', '', 'USER')->where(['id' => ['in', '7,22,28,33,43'], 'status' => 1])->field('id,name')->select();
                break;
            case 6://贷后  王智  刘元芬
                $admin = M('admin', '', 'USER')->where(['id' => ['in', '27,39'], 'status' => 1])->field('id,name')->select();
                break;
        }
        $this->ajaxreturn(['code'=>1001,'data'=>$admin],'json');
    }
    /**
     * 创建工单
     * */
    public function add_order()
    {
        $title = I('title');
        $content = I('content');
        $img = I('img');
        $accept_apart_id = I('accept_apart_id');
        $user_name = I('user_name');
        $phone = I('phone');
        if(!empty($phone)){
            $user_vid=M('user', '', 'USER')->where(['mobile' => $phone,'truename'=>$user_name])->getfield('vid');
            if(empty($user_vid)){
                $this->ajaxReturn(array('state' => '2','result'=>'请添加正确的手机号和用户名'), 'json');
            }
        }

        $imgurl='';
        if (!empty($img)) {
            $upload = new \Admin\Logic\UploadPicLogic();        //实例化 上传图片
            $picarray = explode('~', $img);
            $url="kefu/workorder/";
            foreach ($picarray as $k1 => $v1) {
                $returnimg = $upload->LoadIgoodimg($v1,$url);
                if ($returnimg['status'] == '1') {
                    if($k1==0){
                        $imgurl=$returnimg['pic'];
                    }else{
                        $imgurl=$imgurl.','. $returnimg['pic'];
                    }
                } else {
                    $this->ajaxReturn(array('state' => '2','result'=>'图片上传失败'), 'json');
                }
            }
        }
        $apart_id =1;
        $publish_name = $_SESSION['name'];
        //随机选择 该部门任一客服解决
        $where = [];
        $accept_name=I('accept_name');
        M('work_order', '', 'KEFU')->startTrans();
        M('work_order_detail', '', 'KEFU')->startTrans();
        $arr = array('level'=>I('level'),'apart_id' => $apart_id, 'publish_name' => $publish_name, 'accept_apart_id' => $accept_apart_id, 'accept_name' => $accept_name, 'title' => $title, 'user_name' => $user_name, 'user_phone' => $phone, 'ctime' => time(), 'upd_time' => time());
        $add = M('work_order', '', 'KEFU')->add($arr);
        $arr = array('content' => $content, 'img' => $imgurl, 'wo_id' => $add);
        $add1 = M('work_order_detail', '', 'KEFU')->add($arr);
        if ($add && $add1) {
            $arr=array(5,6,7,8,9,10,11,12);
            if(in_array($accept_apart_id,$arr)){//技术
                send_sms('15105876874', '大佬，你有新的工单，请注意查收！【共享现金】');//振业
                send_sms('13587989359', '大佬，你有新的工单，请注意查收！【共享现金】');//莎蓓
            }
            //APP推送
            $app_key = 'dba87c6c10ab941f1e287026'; // appkey
            $master_secret = '0eb2ff195817d4b43915c2ac'; // master_secret
            $client = new \Admin\Service\JPush\Client($app_key, $master_secret);
            $pusher = $client->push();
            $pusher->setPlatform(array('ios', 'android'));
            $pusher->options(['apns_production' => true]);
            $pusher->addTagAnd($accept_apart_id);
            $pusher->setNotificationAlert('你有新的工单需要处理');
            try {
                $pusher->send();
            } catch (\Admin\Service\JPush\Exceptions\JPushException $e) {
                print $e;
            }
            M('work_order', '', 'KEFU')->commit();
            M('work_order_detail', '', 'KEFU')->commit();
            add_log('创建工单'.$add);
            $this->ajax('1001', '添加成功');
            die;
        }else{
            M('work_order', '', 'KEFU')->rollback();
            M('work_order_detail', '', 'KEFU')->rollback();
            $this->ajax('1002', '添加失败');
        }
    }


    /**
      工单详情
     */
    public function details(){
        $id = I('get.id');
        $info = M('work_order', '', 'KEFU')->join('b join work_order_detail a on b.id=a.wo_id')->where(['b.id' => $id])->field('a.extra_content,b.accept_name,b.apart_id,b.publish_name,b.accept_apart_id,b.status,b.ctime,a.content,a.img,b.upd_time,b.user_name,b.user_phone')->find();
        $status = $info['status'];
        $this->apart_id=$info['apart_id'];
        $this->name=$_SESSION['name'];
        $this->accept_apart_id=$info['accept_apart_id'];
        if($info['apart_id']==1 && $info['publish_name']==$_SESSION['name']){
            $type=3;
        }elseif($info['accept_apart_id']==1 && $info['accept_name']==$_SESSION['name']){
            if($info['status']==1 || $info['status']==2){
                $type=2;
            }
            if($info['status']==3){
                $type=4;
            }
        }elseif($info['accept_apart_id']==1 && $info['accept_name']!=$_SESSION['name']&& ($info['status']==1||$info['status']==2)){
            $type=5;
        }

        $apart_f = M('apart', '', 'KEFU')->where(['id' => $info['apart_id']])->getField('name');
        $apart_s = M('apart', '', 'KEFU')->where(['id' => $info['accept_apart_id']])->getField('name');
        $info['apart_id'] = $apart_f;
        $info['accept_apart_id'] = $apart_s;
        $info['ctime'] = date('Y-m-d H:i', $info['ctime']);
        switch ($info['status']){
            case 1:$info['status']='待处理';break;
            case 2:$info['status']='已回复';break;
            case 3:$info['status']='已完成';break;
            case 4:$info['status']='已取消';break;
            case 5:$info['status']='已删除';break;
        }
        if(!empty($info['img'])){
            $images = explode(',', $info['img']);
        }else{
            $images='';
        }
        $apart = M('apart', '', 'KEFU')->where(['id'=>['neq',3]])->select();
        $this->admin=M('admin', '', 'KEFU')->where(['role_id'=>['in','1,2'],'status'=>1])->field('id,name')->order('id desc')->select();
//            //操作记录
        $record_feedback = M('work_order_answer', '', 'KEFU')->join('b join apart a on b.apart_id = a.id')->where(['w_id' => $id])->field('a.name as apart_name,b.name,b.content,b.ctime,b.img')->select();//回复记录
        foreach ($record_feedback as $k => $v) {
            $record_feedback[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
            $record_feedback[$k]['type'] = '1';
            $record_feedback[$k]['img'] = explode(',',$v['img']);
        }
        $record_log = M('work_order_log', '', 'KEFU')->join('b join apart a on b.apart_id = a.id')->where(['work_id' => $id])
            ->field('a.name as apart_name,b.change_name as name,b.accept_apart_id as content,b.ctime')->select();//转交记录
        foreach ($record_log as $k => $v) {
            $record_log[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
            $record_log[$k]['type'] = '2';
            $record_log[$k]['img'] = '';
        }
        $total = array_merge($record_feedback, $record_log);
        $time = array();
        foreach ($total as $k) {
            $time[] = $k['ctime'];
        }
        array_multisort($time, SORT_ASC, $total);
        if($status==3 || $status==4){
            $s_arr['apart_name']=$_SESSION['name'];
            $s_arr['accept_apart_id']='客服部门';
            $s_arr['ctime']=$info['upd_time'];
            $s_arr['type']=$status;
            $s_arr['img'] = '';
            array_push($total,$s_arr);
        }
        $this->assign(array(
            'data' => $info,
            'type' => $type,
            'imgs1' => $images,
            'apart' => $apart,
            'id' => $id,
            'status' => $status,
            'work_log' => $total
        ));
        $this->display();
    }
    /**
     * 完结工单
     */
    public function workorder_finish()
    {
        $id = I('id');
        $info = M('work_order', '', 'KEFU')->where(['id' => $id])->setfield('status', '3');
        if ($info) {
            add_log('完结工单' . $id);
            $update = M('work_order', '', 'KEFU')->where(['id' => $id])->setfield('upd_time', time());//工单更新时间
            $this->ajaxReturn(['code' => '1001', 'result' => '完成']);
            die;
        }
        $this->ajaxReturn(['code' => '1002', 'result' => '失败']);
    }

    /**
     *上传图片
     */

    public function uploadimg(){
        if (empty($_FILES)) {
            $this->ajaxReturn(['code' => '1002', 'result' => '无图']);
        } else {
            $image=$_FILES['uploadimg'];
            $url='http://gxxj.oss-cn-hangzhou.aliyuncs.com';
            $success = new \Service\OssClient('LTAI6sZcsEa0SGHc','053o9lXKyeLh1J1nmlykMg0z8N0Q5E',$url);
            $ext = strtolower(trim(substr($image['name'], strrpos($image['name'], '.')), '.'));
            $image['name'] = md5(time() . uniqid());
            $object = 'adm/'.$image['name'].'.'.$ext;
            $filePath = $image['tmp_name'];

            try {
                $success->uploadFile('gxxj',$object,$filePath);
                $res= $url.'/adm/'.$image['name'].'.'.$ext;
                $data['pic']=$res;
            } catch (Exception $e) {
                printf(__FUNCTION__ . ": FAILED\n");
                printf($e->getMessage() . "\n");
                $res= '1003';
            }

            if($res=='1002'){
                $data['code']='1002';
                $data['result']='图片不得大于2M';
            }else{
                $data['code']='1001';
                $data['result']=$res;
            }
            add_log('回复工单上传图片');
            $this->ajaxReturn($data);
        }
    }

    /**
     * 工单详情 回复
     */
    public function workorder_feedback(){

        $id = I('id');
        $content = I('back_content');
        $img = I('img');
        $arr = array('w_id' => $id, 'apart_id' => 1, 'name' => $_SESSION['name'], 'content' => $content, 'img' => $img, 'ctime' => time());
        $wo=M('work_order', '', 'KEFU')->where(['id' => $id])->field('apart_id,publish_name,status')->find();
        M('work_order_answer', '', 'KEFU')->startTrans();
        M('work_order', '', 'KEFU')->startTrans();
        $info = M('work_order_answer', '', 'KEFU')->add($arr);
        if ($info) {
            if( $wo['publish_name']!=$_SESSION['name']&&$wo['status']==1){
                $data['status']=2;
            }
            $data['upd_time']=time();
            if(! M('work_order', '', 'KEFU')->where(['id' => $id])->save($data)){//工单更新时间
                M('work_order_answer', '', 'KEFU')->rollback();
                M('work_order', '', 'KEFU')->rollback();
            }
            add_log( '回复工单' . $id . '记录为' . $info);
            M('work_order_answer', '', 'KEFU')->commit();
            M('work_order', '', 'KEFU')->commit();

            //回复工单推送
            if($wo['publish_name']!=$_SESSION['name']){

            $app_key = 'dba87c6c10ab941f1e287026'; // appkey
            $master_secret = '0eb2ff195817d4b43915c2ac'; // master_secret
            $client = new \Admin\Service\JPush\Client($app_key, $master_secret);
            $pusher = $client->push();
            $pusher->setPlatform(array('ios', 'android'));
            $pusher->options(['apns_production' => true]);
            $pusher->addAlias(trim($_SESSION['id']));
            $pusher->setNotificationAlert('您的工单有新的回复，请查看');
            try {
                $pusher->send();
            } catch (\Admin\Service\JPush\Exceptions\JPushException $e) {
                print $e;
            }
            }
            $this->ajaxReturn(['code' => '1001', 'result' => '回复成功']);

            die;
        }
        M('work_order_answer', '', 'KEFU')->rollback();
        M('work_order', '', 'KEFU')->rollback();
        $this->ajaxReturn(['code' => '1002', 'result' => '回复失败']);
    }

    /**
     * 补充说明
     */
    public function extra_content(){
        $id = I('id');
        $data['extra_content']=I('extra_content');
        if(M('work_order_detail', '', 'KEFU')->where(['wo_id'=>$id])->save($data)){
            $str = array('aid' => $_SESSION['id'], 'content' => '工单' . $id.'修改补充说明', 'ctime' => time());
            M('admin_log', '', 'KEFU')->add($str);
            $this->ajaxreturn(['code'=>1001,'result'=>'工单补充说明编辑成功'],'json');
        }else{
            $this->ajaxreturn(['code'=>1002,'result'=>'工单补充说明编辑失败'],'json');
        }
    }
    /**
     * 转交工单
     */
    public function workorder_turn(){
        if (!IS_POST) {
            $this->ajaxReturn(['status' => '3', 'result' => '操作异常'], 'json');
        }
        $apart=I('apart');
        $wk_id=I('work_id');
        M('work_order_log','','KEFU')->startTrans();
        M('work_order','','KEFU')->startTrans();
        $arr=array();
        $order=M('work_order','','KEFU')->where(['id'=>I('work_id')])->field('title,apart_id,publish_name,accept_apart_id,accept_name')->find();
        $adminwhere['status']=1;
        $data['accept_name']=I('accept_name');
        $data['apart_id']=1;
        $data['work_id']=$wk_id;
        $data['accept_apart_id']=$apart;
        $data['change_name']=$_SESSION['name'];
        $data['ctime']=time();
        if(M('work_order_log','','KEFU')->add($data)){
            $orderdata['upd_time']=time();
            $orderdata['accept_apart_id']=$apart;
            $orderdata['accept_name']=$data['accept_name'];
            if(M('work_order','','KEFU')->where(['id'=>$wk_id])->save($orderdata)){
                M('work_order_log','','KEFU')->commit();
                M('work_order','','KEFU')->commit();
                $str = array('aid' => $_SESSION['id'], 'content' => '转交工单' . I('work_id'), 'ctime' => time());
                M('admin_log', '', 'KEFU')->add($str);
                $this->ajaxReturn(['code' => '1001', 'result' => '转交成功']);
            }else{
                M('work_order_log','','KEFU')->rollback();
                M('work_order','','KEFU')->rollback();
                $this->ajaxReturn(['code' => '1002', 'result' => '转交失败']);
            }
        }else{
            M('work_order_log','','KEFU')->rollback();
            M('work_order','','KEFU')->rollback();
            $this->ajaxReturn(['code' => '1002', 'result' => '转交失败','err'=>$data]);
        }
    }

    /**
     * 关闭工单
     */
    public function close(){
        $id=I('id');
        if(M('work_order', '', 'KEFU')->where(['id'=>$id])->save(['status'=>4])){
            add_log('工单' . $id.'关闭');
            $this->ajaxreturn(['code'=>1001,'result'=>'关闭工单成功'],'json');
        }else{
            $this->ajaxreturn(['code'=>1002,'result'=>'关闭工单失败'],'json');
        }
    }
}